﻿//=================================================
// Copyright (C) 2011 iSun Studio 软件工作室
// 作 者：江怀玉
// 日 期：2011-10-14
// 描 述：页面基类，所有的aspx页面继承自基类
//        页面基类提供常用的方法和常用的用户信息
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
// 1.00   2011/10/11   江怀玉           
//=================================================

using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using iSun.Model;
using iSun.Common;
using iSun.Web.UI.Controls;
using iSun.BLL.Base;
using iSun.Entity;
using System.Reflection;
using System.Collections.Generic;
using System.Collections;
using System.Text;

namespace iSun.Web.UI.Controls
{
    public class DojoDefineForm : BasePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            //this.CreateEntitysInstance();
        }


        public string ID
        {
            get
            {
                return GetStringFromQueryString("EntityID", "");
            }
        }



        #region 对象操作
        /// <summary>
        /// 当前实体类
        /// </summary>
        public BaseEntity CurrEntity
        {
            get;
            set;
        }


        /// <summary>
        /// 创建实体对象实例
        /// </summary>
        public void CreateEntitysInstance()
        {
            try
            {
                CreateEntitysInstance(EntityName);
            }
            catch { }
        }

        /// <summary>
        /// 创建实体对象实例
        /// </summary>
        /// <param name="classname"></param>
        public void CreateEntitysInstance(string EntityName)
        {
            try
            {
                BaseEntity _entitys =  Reflection.CreateEntitysInstance( EntityName) as BaseEntity;
                CurrEntity = _entitys;
            }
            catch (System.Exception ex)
            {

            }
        }
        #endregion


        #region 相关标识
        /// <summary>
        /// 数据的操作方法 insert / update / delete
        /// </summary>
        public virtual string DataAction
        {
            get
            {
                string id = this.GetStringFromQueryString("id", "");
                if (id == "")
                {
                    return "insert";
                }
                else
                {
                    return "update";
                }
            }
        }
        #endregion


        #region 相关网页信息
        /// <summary>
        /// 获得当前FORM,以便可以该控件容器下添加控件.
        /// </summary>
        /// <returns></returns>
        public System.Web.UI.HtmlControls.HtmlForm GetFormOjbect()
        {
            return GetFormOjbect("Form1");
        }

        public System.Web.UI.HtmlControls.HtmlForm GetFormOjbect(string FormName)
        {
            Control ctrl = new Control();
            ctrl = this.Page.FindControl(FormName);
            if (ctrl is HtmlForm)
            {
                return (HtmlForm)ctrl;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取当前的网页名
        /// </summary>
        /// <returns>返文件名</returns>
        public string GetPageFilePath()
        {
            string str = this.Request.Url.AbsolutePath;
            str = this.Request.RawUrl;
            string[] _StrPageName = this.Request.RawUrl.Split('/');
            return _StrPageName[_StrPageName.Length - 1];
        }


        /// <summary>
        /// 获得客户端IP
        /// </summary>
        /// <returns></returns>
        public string GetClietIp()
        {
            return Request.UserHostAddress;
        }

        /// <summary>
        /// 获得当前的网页的地址
        /// </summary>
        /// <param name="AspxFile"></param>
        /// <returns></returns>
        public string GetPageUrl1(string AspxfileName)
        {
            string str = Request.ApplicationPath;
            str += Request.RawUrl;
            return str;
        }



        /// <summary>
        /// 获取当前网页的虚拟地址
        /// </summary>
        /// <returns></returns>
        public string GetPagePath()
        {
            return this.Request.Path;

        }

        /// <summary>
        /// 获取相关信息
        /// </summary>
        /// <param name="Query"> QueryString </param>
        /// <returns></returns>
        public string GetQueryString(string Query)
        {
            try
            {
                string QueryString = Request.QueryString[Query].ToString();
                return QueryString;
            }
            catch (System.Exception e)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获得最后一级目录
        /// </summary>
        /// <returns></returns>
        public string GetCatalog()
        {
            string[] Catalog = GetPagePath().Split('/');
            return Catalog[Catalog.Length - 2];
        }


        /// <summary>
        /// 通过NAME获得对应的控件的值.
        /// </summary>
        /// <param name="Name"></param>
        public string GetContrlValueByName(string Name)
        {
            string strValue = Request.Form[Name].Trim();
            return strValue;
        }


        #endregion

        #region 创建对应的实体对象
        /// <summary>
        /// 创建对应的实体对象
        /// </summary>
        /// <param name="instance">实体</param>
        /// <param name="entity">New Entity</param>
        /// <returns></returns>
        public virtual string JsClientInstance(BaseEntity instance, BaseEntity entity)
        {
            if (entity == null)
            {
                if (!(instance is DataTableBaseEntity))
                {
                    return ("var instance=[" + instance.ToJSON() + "];");
                }
                else
                {
                    return ("var instance=[" + (instance as DataTableBaseEntity).EntityJson + "];");
                }

            }
            else
            {
                if (!(entity is DataTableBaseEntity))
                {
                    return ("var instance=[" + entity.ToJSON() + "];");
                }
                else
                {
                    return ("var instance=[" + (entity as DataTableBaseEntity).EntityJson + "];");
                }
                //return ("var instance=[" + entity.ToJSON().Replace("\n", "[BR]").Replace("\r", "") + "];");
            }
        }

        public string  getEntityInstance(BaseEntity instance, BaseEntity entity)
        {
            if (entity == null)
            {
                if (!(instance is DataTableBaseEntity))
                {
                    return ( instance.ToJSON());
                }
                else
                {
                    return ((instance as DataTableBaseEntity).EntityJson );
                }

            }
            else
            {
                if (!(entity is DataTableBaseEntity))
                {
                    return ( entity.ToJSON());
                }
                else
                {
                    return ( (entity as DataTableBaseEntity).EntityJson );
                }
                //return ("var instance=[" + entity.ToJSON().Replace("\n", "[BR]").Replace("\r", "") + "];");
            }
        }
        #endregion

        #region
        /// <summary>
        /// 数据初始化
        /// </summary>
        public virtual void DataInit()
        {

        }



        public virtual string CreateDictinaryInfo()
        {
            string strEntity = this.GetStringFromQueryString("entity", "E_Menu");
            string action = this.GetStringFromQueryString("action", "");
            string strFormID = this.GetStringFromQueryString("formid", Guid.Empty.ToString());
            string id = this.GetStringFromQueryString("id", "");
            BaseEntity instance = iSun.Common.Globals.getEntity(strEntity) as BaseEntity;
            //MasterEntity = instance;
            BaseBussnies bInstance = new iSun.BLL.Base.BaseBussnies(instance);
            //BaseEntity entity = null;
            string tempCondition = strFormID.Trim() == string.Empty || strFormID.Trim() == Guid.Empty.ToString() ? "FormID='" + strFormID + "' or MasterTableName='" + strEntity + "'" : "FormID='" + strFormID + "'";
            iSun.Entity.SysCustomDefineForm FormEntity = bInstance.GetEntityByCondition<SysCustomDefineForm>(tempCondition);
            string tempCondition2 = strFormID.Trim() == string.Empty || strFormID.Trim() == Guid.Empty.ToString() ? "FormID='" + strFormID + "' or TableName='" + strEntity + "'" : "FormID='" + strFormID + "'";
            IList<iSun.Entity.SysFieldItem> dsList = bInstance.GetEntitys<SysFieldItem>(tempCondition2);

            //用于处理
            return  CreateUIData(dsList);
            //return "";

        }


        /// <summary>
        /// 创建下拉数据对象
        /// </summary>
        /// <param name="dsList"></param>
        /// <returns></returns>
        private string CreateUIData(IList<iSun.Entity.SysFieldItem> fieldList)
        {
            StringBuilder _jsDictionaryData = new StringBuilder("");
            string template = "var ds_{0}={1};\r\n";
            BaseBussnies instance = new BaseBussnies();
            foreach (var field in fieldList)
            {
                switch(field.DataSourceType.ToLower())
                {
                    case "json":
                        _jsDictionaryData.Append( string.Format(template, field.FieldName, field.DataSource));
                        break;
                    case "dic":

                        var dic = instance.GetEntitysBySqlComm<Dictionary>(string.Format("Exec [dbo].[sp_GetDicList] '{0}'", field.DataSource));
                        _jsDictionaryData.Append(string.Format(template, field.FieldName,iSun.Common.Globals.getJSON(dic)));   
                        break;
                    case "sql":
                        var dicSql = instance.GetEntitysBySqlComm<Dictionary>(field.DataSource.Replace("[B]", "'"));
                        _jsDictionaryData.Append(string.Format(template, field.FieldName, iSun.Common.Globals.getJSON(dicSql))); 
                        break;
                    default:
                        _jsDictionaryData.Append(string.Format(template, field.FieldName, field.DataSource));
                        break;
                }
            }
            return _jsDictionaryData.ToString();
        }
        #endregion
    }
}
